//
//  SISSHouseProjectPriceTrendView.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/10/18.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSHouseProjectPriceTrendView.h"
#import <Charts/Charts-Swift.h>
#import "SISSDateValueFormatter.h"
#import "SISSProjectChartModel.h"


@interface SISSHouseProjectPriceTrendView ()<UIScrollViewDelegate>

@property (weak, nonatomic) UILabel *titleLabel;
@property (weak, nonatomic) UILabel *middleTitleLabel;
/// middleHorizontalLine
@property (weak, nonatomic) UIView *middleHorizontalLine;
@property (weak, nonatomic) UIView *middleVerticalLine;
/// lineChartView
@property (strong, nonatomic) LineChartView *lineChartView;

/// bottomTag
@property (weak, nonatomic) UIView *leftBottomView;
@property (weak, nonatomic) UILabel *leftBottomLabel;
@property (weak, nonatomic) UIView *middleBottomView;
@property (weak, nonatomic) UILabel *middleBottomLabel;
@property (weak, nonatomic) UIView *rightBottomView;
@property (weak, nonatomic) UILabel *rightBottomLabel;

/// 数据
@property (strong, nonatomic) NSArray<NSDictionary *> *dataArr;

@end
@implementation SISSHouseProjectPriceTrendView

- (void)setBpcleList:(NSArray<SISSProjectChartModel *> *)bpcleList {
    _bpcleList = bpcleList;
    
    NSInteger maxY = 0;
    NSMutableArray *dataArrM = [NSMutableArray arrayWithCapacity:bpcleList.count];
    NSArray *xArr = [NSArray array];
    for (SISSProjectChartModel *projectChartModel in bpcleList) {
        NSMutableArray *x = [NSMutableArray arrayWithCapacity:projectChartModel.list.count];
        NSMutableArray *point = [NSMutableArray arrayWithCapacity:projectChartModel.list.count];
        for (SISSProjectChartPointModel * pointModel in projectChartModel.list) {
            [x addObject:pointModel.date];
            [point addObject:pointModel.avgPrice];
            if ([pointModel.avgPrice integerValue] > maxY) {
                maxY = [pointModel.avgPrice integerValue];
            }
        }
        NSLog(@"建筑形式: %@",projectChartModel.btype);
        NSLog(@"物业类型: %@",projectChartModel.htype);
        NSLog(@"X: %@",x);
        NSLog(@"Y: %@",point);
        [dataArrM addObject:@{@"title": [NSString stringWithFormat:@"%@-%@",projectChartModel.htype,projectChartModel.btype],
                              @"point": point
                              }];
        xArr = x.copy;
    }
    self.dataArr = dataArrM.copy;
     WeakSelf
    if (bpcleList.count != 0) {
        self.lineChartView.xAxis.valueFormatter = [[SISSDateValueFormatter alloc] initWithArr:xArr];
    } else {
        // 没有图表数据时配合controller隐藏
        [self.middleBottomLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.lineChartView.mas_bottom);
            make.centerX.equalTo(weakSelf.mas_centerX);
        }];
    }
    CGFloat maxPrice = maxY + 5000;
    CGFloat minPrice = 0;
    
    self.lineChartView.leftAxis.axisMaximum = maxPrice;
    self.lineChartView.leftAxis.axisMinimum = minPrice;
   
   
    [self.middleVerticalLine mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf).offset(weakSelf.lineChartView.leftAxis.requiredSize.width-0.5);
    }];
    
    if (bpcleList.count == 2) { // 只有两组数据的时候
        [self.middleBottomLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.lineChartView.mas_bottom);
            make.left.equalTo(weakSelf.mas_centerX).offset(3 * globelMargin);
            make.bottom.equalTo(weakSelf).offset(-2 * globelMargin);
        }];
    }

    
    [self updateChartData];
}

- (void)initUI {
    [super initUI];
    
    UILabel *titleLabel = [UILabel yyr_labelWithText:@"价格走势" fontSize:18 textColor:MAIN_TEXT_COLOR];
    [self addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    UILabel *middleTitleLabel = [UILabel yyr_labelWithText:@"" fontSize:15 textColor:COLOR(0xE59335)];
    [self addSubview:middleTitleLabel];
    self.middleTitleLabel = middleTitleLabel;
    
    UIView *middleHorizontalLine = [[UIView alloc] init];
    middleHorizontalLine.backgroundColor = COLOR(0xE59335);
    [self addSubview:middleHorizontalLine];
    self.middleHorizontalLine = middleHorizontalLine;
    
    UIView *middleVerticalLine = [[UIView alloc] init];
    middleVerticalLine.backgroundColor = COLOR(0xB5B5B5);
    [self addSubview:middleVerticalLine];
    self.middleVerticalLine = middleVerticalLine;
    
    // 创建折线图
    self.lineChartView = [[LineChartView alloc] init];
    self.lineChartView.legend.form = ChartLegendFormNone; //说明图标
    self.lineChartView.dragEnabled = YES; // 拖动手势
    self.lineChartView.pinchZoomEnabled = YES; //捏合手势
    self.lineChartView.rightAxis.enabled = NO;// 显示右Y轴
    self.lineChartView.chartDescription.enabled = NO; //不显示描述label
    self.lineChartView.scaleYEnabled = NO; //取消Y轴缩放
//    self.lineChartView.drawGridBackgroundEnabled = YES;
//    self.lineChartView.drawBordersEnabled = YES;
    self.lineChartView.doubleTapToZoomEnabled = YES; // 允许双击缩放
    self.lineChartView.chartDescription.enabled = NO;
    
    [self addSubview:self.lineChartView];
    
    //    self.lineChartView.chartDescription.text = @"dlgjgjj";
    self.lineChartView.legend.enabled = YES;
    
    ChartLegend *legend = self.lineChartView.legend;
    legend.form = ChartLegendFormNone;
    
    legend.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:11.f];
    legend.textColor = UIColor.whiteColor;
    legend.horizontalAlignment = ChartLegendHorizontalAlignmentLeft;
    legend.verticalAlignment = ChartLegendVerticalAlignmentBottom;
    legend.orientation = ChartLegendOrientationHorizontal;
    legend.drawInside = NO;
    
    ChartXAxis *xAxis = self.lineChartView.xAxis;
    xAxis.labelFont = [UIFont systemFontOfSize:8.f];
    xAxis.labelTextColor = UIColor.redColor;
    xAxis.drawGridLinesEnabled = NO;
    xAxis.drawAxisLineEnabled = NO;
    xAxis.labelPosition = XAxisLabelPositionBottom;
     // 设置左右两边有间隙
    xAxis.granularity = 1.0;
    xAxis.spaceMin = xAxis.granularity / 2;
    xAxis.spaceMax = xAxis.granularity / 2;
    //X轴上面需要显示的数据
//    NSMutableArray *xVals = [[NSMutableArray alloc] init];
//
//    for (int i = 1; i <= 12; i++) {
//        [xVals addObject: [NSString stringWithFormat:@"2018-%d",i]];
//    }
//    xAxis.valueFormatter = [[SISSDateValueFormatter alloc] initWithArr:xVals];
    
    ChartYAxis *leftAxis = self.lineChartView.leftAxis;
    leftAxis.axisLineColor = COLOR(0xB5B5B5);
    leftAxis.labelTextColor = MAIN_TEXT_COLOR;
    leftAxis.labelFont = [UIFont systemFontOfSize:8];
    leftAxis.axisMaximum = 92800;
    leftAxis.axisMinimum = 0;
    leftAxis.forceLabelsEnabled = YES;// 强制绘制指定数量的label
    leftAxis.drawGridLinesEnabled = YES;
    leftAxis.drawZeroLineEnabled = NO;
    leftAxis.granularityEnabled = YES;
    
    // 只滑动不缩放：（系统内部默认是先缩放后滑动）及初始化时x轴就缩放2倍,
    ChartViewPortHandler *scaleX = self.lineChartView.viewPortHandler;
    [scaleX setMinimumScaleX:2];
    [scaleX centerViewPortWithPt:CGPointMake(0, self.lineChartView.bounds.size.width) chart:self.lineChartView];

    [self.lineChartView setVisibleXRangeMinimum:5];
    [self.lineChartView setVisibleXRangeMaximum:12];
    
    // 设置数据滚动到最右边
    [self.lineChartView centerViewToXValue:2000 yValue:self.lineChartView.center.y axis:AxisDependencyLeft];
    
    UIView *leftBottomView = [[UIView alloc] init];
    leftBottomView.layer.cornerRadius = 2;
    leftBottomView.layer.masksToBounds = YES;
    leftBottomView.hidden = YES;
    [self addSubview:leftBottomView];
    self.leftBottomView = leftBottomView;
    UILabel *leftBottomLabel = [UILabel yyr_labelWithText:@"" fontSize:15 textColor:MAIN_TEXT_COLOR];
    leftBottomLabel.hidden = YES;
    [self addSubview:leftBottomLabel];
    self.leftBottomLabel = leftBottomLabel;
    
    UIView *middleBottomView = [[UIView alloc] init];
    middleBottomView.layer.cornerRadius = 2;
    middleBottomView.layer.masksToBounds = YES;
    middleBottomView.hidden = YES;
    [self addSubview:middleBottomView];
    self.middleBottomView = middleBottomView;
    UILabel *middleBottomLabel = [UILabel yyr_labelWithText:@"" fontSize:15 textColor:MAIN_TEXT_COLOR];
    middleBottomLabel.hidden = YES;
    [self addSubview:middleBottomLabel];
    self.middleBottomLabel = middleBottomLabel;
    
    UIView *rightBottomView = [[UIView alloc] init];
    rightBottomView.layer.cornerRadius = 2;
    rightBottomView.layer.masksToBounds = YES;
    rightBottomView.hidden = YES;
    [self addSubview:rightBottomView];
    self.rightBottomView = rightBottomView;
    UILabel *rightBottomLabel = [UILabel yyr_labelWithText:@"" fontSize:15 textColor:MAIN_TEXT_COLOR];
    rightBottomLabel.hidden = YES;
    [self addSubview:rightBottomLabel];
    self.rightBottomLabel = rightBottomLabel;
}

- (void)initConstraint {
    [super initConstraint];
    
    CGSize bottomTagSize = CGSizeMake(12, 6);
    WeakSelf
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(weakSelf).offset(2 * globelMargin);
    }];
    
    [self.middleTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf);
        make.bottom.equalTo(weakSelf.middleHorizontalLine.mas_top);
    }];
    
    [self.middleHorizontalLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.titleLabel.mas_bottom).offset(2 * globelMargin);
        make.left.right.equalTo(weakSelf);
        make.height.mas_equalTo(2);
    }];
    
    [self.middleVerticalLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.middleHorizontalLine.mas_bottom);
        make.left.equalTo(weakSelf).offset(weakSelf.lineChartView.leftAxis.requiredSize.width-0.5);
        make.width.mas_equalTo(0.5);
        make.height.mas_equalTo(5 * globelMargin);
    }];
  
    [self.lineChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.middleVerticalLine.mas_bottom).offset(-1.25 * globelMargin);
        make.height.mas_equalTo(200);
        make.left.equalTo(weakSelf);
        make.right.equalTo(weakSelf).offset(2 * globelMargin);
//        make.bottom.equalTo(weakSelf).offset(-2 * globelMargin);
    }];

    [self.middleBottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.lineChartView.mas_bottom);
        make.centerX.equalTo(weakSelf.mas_centerX);
        make.bottom.equalTo(weakSelf).offset(-2 * globelMargin);
    }];
    
    [self.middleBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.middleBottomLabel.mas_left).offset(-0.2 * globelMargin);
        make.centerY.equalTo(weakSelf.middleBottomLabel);
        make.size.mas_equalTo(bottomTagSize);
    }];
    
    [self.leftBottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.middleBottomView.mas_left).offset(-2 * globelMargin);
        make.centerY.equalTo(weakSelf.middleBottomLabel);
    }];
    
    [self.leftBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.leftBottomLabel);
        make.right.equalTo(weakSelf.leftBottomLabel.mas_left).offset(-0.2 * globelMargin);
        make.size.mas_equalTo(bottomTagSize);
    }];
    
    [self.rightBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.middleBottomLabel);
        make.left.equalTo(weakSelf.middleBottomLabel.mas_right).offset(2 * globelMargin);
        make.size.mas_equalTo(bottomTagSize);
    }];

    [self.rightBottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.rightBottomView.mas_right).offset(0.2 * globelMargin);
        make.centerY.equalTo(weakSelf.middleBottomLabel);
    }];
}

- (void)updateChartData {
    
    UIColor *firstColor = COLOR(0xE59335);
    UIColor *secondColor = [UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f];
    UIColor *thirdColor = [UIColor colorWithRed:244/255.f green:117/255.f blue:117/255.f alpha:1.f];
    
    self.leftBottomView.backgroundColor = firstColor;
    self.middleBottomView.backgroundColor = secondColor;
    self.rightBottomView.backgroundColor = thirdColor;
    
    // 对应Y轴上面需要显示的数据
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    NSMutableArray *yVals2 = [[NSMutableArray alloc] init];
    NSMutableArray *yVals3 = [[NSMutableArray alloc] init];
    
    for (NSInteger i = 0; i < self.dataArr.count; i++) {
        NSDictionary *dict = self.dataArr[i];
        if (i == 0) {
            self.middleBottomView.hidden = NO;
            self.middleBottomLabel.hidden = NO;
            self.middleBottomLabel.text = dict[@"title"];
            NSArray *point = dict[@"point"];
            for (int j = 0; j < point.count; j++) {
                int a = [point[j] intValue];
                ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:j y:a];
                [yVals1 addObject:entry];
            }
        } else if (i == 1) {
            self.leftBottomView.hidden = NO;
            self.leftBottomLabel.hidden = NO;
            self.leftBottomLabel.text = dict[@"title"];
            NSArray *point = dict[@"point"];
            for (int j = 0; j < point.count; j++) {
                int a = [point[j] intValue];
                ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:j y:a];
                [yVals2 addObject:entry];
            }
        }else if (i == 2) {
            self.rightBottomView.hidden = NO;
            self.rightBottomLabel.hidden = NO;
            self.rightBottomLabel.text = dict[@"title"];
            NSArray *point = dict[@"point"];
            for (int j = 0; j < point.count; j++) {
                int a = [point[j] intValue];
                ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:j y:a];
                [yVals3 addObject:entry];
            }
        }
    }
    
    LineChartDataSet *set1 = nil, *set2 = nil, *set3 = nil;
    
    if (self.lineChartView.data.dataSetCount > 3) {
        set1 = (LineChartDataSet *)self.lineChartView.data.dataSets[0];
        set2 = (LineChartDataSet *)self.lineChartView.data.dataSets[1];
        set3 = (LineChartDataSet *)self.lineChartView.data.dataSets[2];
        [set1 replaceEntries:yVals1];
        [set2 replaceEntries:yVals2];
        [set3 replaceEntries:yVals3];
//        set1.values = yVals1;
//        set2.values = yVals2;
//        set3.values = yVals3;
        [self.lineChartView.data notifyDataChanged];
        [self.lineChartView notifyDataSetChanged];
    } else {
        set1 = [[LineChartDataSet alloc] initWithEntries:yVals1 label:@"DataSet 1"];
        //自定义set的各种属性
        //设置折线的样式
        set1.drawIconsEnabled = YES;
        set1.formLineWidth = 1.1;//折线宽度
        set1.formSize = 15.0;
        set1.drawValuesEnabled = YES;//是否在拐点处显示数据
//        set1.valueColors = @[[UIColor blackColor]];//折线拐点处显示数据的颜色
        [set1 setColor:firstColor];//折线颜色
        //折线拐点样式
        set1.drawCirclesEnabled = YES;//是否绘制拐点
        set1.axisDependency = AxisDependencyLeft;
//        [set1 setColor:[UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f]];
        [set1 setCircleColor:firstColor];
        set1.lineWidth = 1.2;
        set1.circleRadius = 3.0;
//        set1.fillAlpha = 65/255.0;
//        set1.fillColor = [UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f];
//        set1.highlightColor = [UIColor colorWithRed:244/255.f green:117/255.f blue:117/255.f alpha:1.f];
        set1.drawCircleHoleEnabled = NO;
        
        set2 = [[LineChartDataSet alloc] initWithEntries:yVals2 label:@"DataSet 2"];
        //自定义set的各种属性
        //设置折线的样式
        set2.drawIconsEnabled = YES;
        set2.formLineWidth = 1.1;//折线宽度
        set2.formSize = 15.0;
        set2.drawValuesEnabled = YES;//是否在拐点处显示数据
//        [set2 setColor:RGB(248, 144, 28)];//折线颜色
        //折线拐点样式
        set2.drawCirclesEnabled = YES;//是否绘制拐点
        set2.valueTextColor = [UIColor redColor];
        set2.axisDependency = AxisDependencyLeft;
        [set2 setColor:secondColor];
        [set2 setCircleColor:secondColor];
        set2.lineWidth = 1.2;
        set2.circleRadius = 3.0;
//        set2.fillAlpha = 65/255.0;
//        set2.fillColor = UIColor.redColor;
//        set2.highlightColor = [UIColor colorWithRed:244/255.f green:117/255.f blue:117/255.f alpha:1.f];
        set2.drawCircleHoleEnabled = NO;
        
        set3 = [[LineChartDataSet alloc] initWithEntries:yVals3 label:@"DataSet 3"];
        //自定义set的各种属性
        //设置折线的样式
        set3.drawIconsEnabled = YES;
        set3.formLineWidth = 1.1;//折线宽度
        set3.formSize = 15.0;
        set3.drawValuesEnabled = YES;//是否在拐点处显示数据
        set3.valueTextColor = [UIColor blackColor];
//        [set2 setColor:RGB(248, 144, 28)];//折线颜色
        //折线拐点样式
        set3.drawCirclesEnabled = YES;//是否绘制拐点
        set3.axisDependency = AxisDependencyLeft;
        [set3 setColor:thirdColor];
        [set3 setCircleColor:thirdColor];
        set3.lineWidth = 1.2;
        set3.circleRadius = 3.0;
//        set2.fillAlpha = 65/255.0;
//        set2.fillColor = UIColor.redColor;
//        set2.highlightColor = [UIColor colorWithRed:244/255.f green:117/255.f blue:117/255.f alpha:1.f];
        set3.drawCircleHoleEnabled = NO;
        
        NSMutableArray *dataSets = [[NSMutableArray alloc] init];
        [dataSets addObject:set1];
        [dataSets addObject:set2];
        [dataSets addObject:set3];
        
        LineChartData *data = [[LineChartData alloc] initWithDataSets:dataSets];
//        [data setValueTextColor:UIColor.redColor]; // 文字颜色
        [data setValueFont:[UIFont systemFontOfSize:9.f]]; // 文字字体
        
        self.lineChartView.data = data;
        
        //这里可以调用一个加载动画即1s出来一个绘制点
        //        [self.lineChartView animateWithXAxisDuration:1.0f];
    }
}


#pragma mark - 懒加载
- (NSArray<NSDictionary *> *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSArray array];
    }
    return _dataArr;
}

@end
